package main

import (
	"fmt"
	"net"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"gitcode.com/shexk/nas/core"
	x "gitee.com/shexk/gtl/net"
)

func main() {
	TextChan := make(chan string, 1000)

	client := x.NewTcpClient()
	dirs := core.NewDirs(TextChan)
	dirs.StartTask()
	client.OnEvent = func(conn net.Conn, state uint8, data []byte, datasize uint16, err error) { //func(conn net.Conn, state int, data []byte, datasize uint32, err error) {
		switch state {
		case x.TCP_STATE_CONNECTED:
			dirs.Conn = conn
			TextChan <- "Connect Success"
		case x.TCP_STATE_DISCONNECTED:
			TextChan <- "Connect Fail,Auto Reconnect..."
			dirs.Conn = nil
		case x.TCP_STATE_DATA:
			dirs.ProcessData(data)
		case x.TCP_STATE_ERROR:
			TextChan <- "Connect Error,Auto Reconnect..."
			dirs.Conn = nil
		}
	}

	client.AutoConnectServer("127.0.0.1:60000")
	myApp := app.New()
	myWindow := myApp.NewWindow("NAS Client")

	tree := widget.NewTree(
		func(id widget.TreeNodeID) []widget.TreeNodeID {
			if id == "" {
				return dirs.RequestDir("")
			}
			return dirs.RequestDir(id)
		},
		func(id widget.TreeNodeID) bool {
			if id == "" {
				return true
			} else {
				return dirs.IsDir(id)
			}
		},
		func(branch bool) fyne.CanvasObject {
			if branch {
				return widget.NewLabel("Branch template")
			}
			return widget.NewLabel("Leaf template")
		},
		func(id widget.TreeNodeID, branch bool, o fyne.CanvasObject) {
			o.(*widget.Label).SetText(dirs.GetFileNameFromFilePath(id))
		},
	)
	selFilePath := ""

	downBtn := widget.NewButton("下载", func() {
		dirs.RequestDownload(selFilePath)
	})
	HitEdit := widget.NewEntry()
	topLay := container.NewHSplit(downBtn, HitEdit)
	topLay.SetOffset(0.1)

	go func() {
		for txt := range TextChan {
			fyne.Do(func() {
				HitEdit.SetText(txt)
			})
		}
	}()

	tree.OnSelected = func(uid string) {
		selFilePath = uid
		HitEdit.SetText(fmt.Sprintf("FileSize=%s", core.GetFormatValue(dirs.GetFileSize(uid))))
	}

	treeLay := container.NewScroll(tree)
	treeLay.SetMinSize(fyne.NewSize(400, 600))

	mainLay := container.NewVBox(topLay, treeLay)

	myWindow.SetContent(mainLay)
	myWindow.CenterOnScreen()
	myWindow.ShowAndRun()
}

//Mac ../../bin/fyne package -os darwin -icon app.ico
//Win fyne package -os windows -icon app.ico
//linux fyne package -os linux -icon myapp.png
